
source('code/analysis/load.R')

data = read_dta('data/working/defund-receiver.dta') %>%  
  mutate(exp = 'defund', credibility = 'credible', expgroup = 'Experiment 2\n(defund, higher credibility)') %>% 
  bind_rows(read_dta('data/working/deport-receiver.dta') %>% mutate(exp = 'deport', expgroup='Experiment 4\n(deport)')) %>% 
  bind_rows(read_dta('data/working/defund-nocredible-receiver.dta') %>% mutate(exp = 'notcredible', credibility = 'notcredible', expgroup='Auxiliary Experiment 7\n(defund, lower credibility)')) %>% 
  data_finalize() %>%
  mutate(deny = !bonus,
         expgroup = factor(expgroup, levels= c('Experiment 2\n(defund, higher credibility)','Auxiliary Experiment 7\n(defund, lower credibility)','Experiment 4\n(deport)')))


main_results = function(data, var) {
  defund = data$exp[1] != 'deport'
  if (defund & var == 'donate') {
    subtitle = "Belief about matched respondent's donation to NAACP"
    label = 'defund-receiver'
  } else if (data$exp[1] == 'deport' & var == 'donate') {
    subtitle = "Belief about matched respondent's donation to BCCRF"
    label = 'deport-receiver'
  } else if (defund & var == 'bonus') {
    subtitle = 'Willingness to deny $1 bonus to matched respondent'
    label = 'defund-receiver'
  } else if (data$exp[1] == 'deport' & var == 'bonus') {
    subtitle = 'Willingness to deny $1 bonus to matched respondent'
    label = 'deport-receiver'
  }
  experiment = ifelse(defund, 'Experiment 2', 'Experiment 4')
  title = 'Inference about and social sanctions toward matched pro-deportation respondent'
  depvar = ifelse(var=='bonus', 'Authorized bonus', 'Believe matched respondent donated')
  
  if (var == 'donate') {
    data$outcome = data$believe_donated
  } else {
    data$outcome = data$deny
  }
  model1 = lm(outcome~excuse, data=data %>% filter(exp!='notcredible'))
  model2 = lm(outcome~excuse+age+I(age^2)+race+hisp+male+education, data=data %>% filter(exp!='notcredible'))


  if (defund) {
    model3 = lm(outcome~excuse, data=data %>% filter(exp=='notcredible'))
    model4 = lm(outcome~excuse+age+I(age^2)+race+hisp+male+education, data=data %>% filter(exp=='notcredible'))

    mean_dv = formatC(mean(data$outcome[data$exp=='defund' & data$excuse==0]), digits=3, format='f')
    mean_nocredible = formatC(mean(data$outcome[data$exp=='notcredible' & data$excuse==0]), digits=3, format='f')
    models = list(model1, model2, model3, model4)
    out = stargazer(models, 
                    omit='age|race|hisp|male|rep|education|Constant|ind|partisan',
                    covariate.labels = c('Cover'),
                    column.labels = c('Higher-credibility', 'Lower-credibility'),
                    column.separate = c(2,2),
                    keep.stat = c('rsq', 'n'), 
                    dep.var.labels = depvar,
                    title = title, 
                    label = str_interp('t:${label}'),
                    add.lines = list(c('Controls', rep(c('No','Yes'), 2))))
    means = str_interp('No Cover mean & ${mean_dv} & ${mean_dv} & ${mean_nocredible} & ${mean_nocredible}\\\\')
    out = c(out[1:18], means, out[19:length(out)])
    out = star_notes_tex(out, note.type = 'threeparttable', note = tablenotes[[label]])
    return(out)
    
  } else {
    mean_dv = formatC(mean(data$outcome[data$excuse==0], na.rm = T), digits=3, format='f')
    models = list(model1, model2)
    out = stargazer(models, 
                    omit='age|race|hisp|male|rep|education|Constant|ind|partisan',
                    covariate.labels = c('Cover'),
                    keep.stat = c('rsq', 'n'), 
                    dep.var.labels = depvar,
                    title = title, 
                    label = str_interp('t:${label}'),
                    add.lines = list(c('Controls', c('No','Yes'))))
    means = str_interp('No Cover mean & ${mean_dv} & ${mean_dv} \\\\')
    out = c(out[1:18], means, out[19:length(out)])
    out = star_notes_tex(out, note.type = 'threeparttable', note = tablenotes[[label]])
    return(out)
  }
  
}


## Table 3 ##
out1 = main_results(data %>% filter(exp!='deport'), 'donate')
out2 = main_results(data %>% filter(exp!='deport'), 'bonus')
out = c(out1[1:4],
        "  \\caption{Inference about and social sanctions toward matched anti-defunding respondent} ",
        ' \\label{t:defund-receiver}',
        out1[7:9],
        out1[14],
        " \\cmidrule(rr){2-3} \\cmidrule(rr){4-5}",  
        out1[15],
        '\\midrule',
        '\\textbf{Panel A:} & \\multicolumn{4}{c}{\\textit{Belief partner donated}} \\\\',
        '\\midrule',
        out1[17:20],
        out1[24], # R-squared
        '\\midrule',
        '\\textbf{Panel B:} & \\multicolumn{4}{c}{\\textit{Denied bonus to partner}} \\\\',
        '\\midrule',
        out2[17:20],
        out2[24], # R-squared
        out2[21:23], # Controls + Obs
        out2[25:length(out2)])

write_lines(out, 'output/tables/defund-receiver.tex')



## Table 4 ##
out1 = readLines('output/tables/deport-sender.tex')
out2 = main_results(data %>% filter(exp=='deport'), 'donate')
out3 = main_results(data %>% filter(exp=='deport'), 'bonus')
out1[12] = '\\textbf{Panel A:} & \\multicolumn{2}{c}{\\textit{Scheduled Tweet}} \\\\ ' 
out2[12] = '\\textbf{Panel B:} & \\multicolumn{2}{c}{\\textit{Belief partner donated}} \\\\'
out3[12] = "\\textbf{Panel C:} & \\multicolumn{2}{c}{\\textit{Denied bonus to partner}} \\\\"
out = c(
  '\\begin{table} \\centering',
  '\\caption{Expression and interpretation of pro-deportation Tweet}',
  '\\label{t:deport}',
  '\\begin{threeparttable}',
  '\\begin{tabular}{@{\\hspace{5pt}}l@{\\hspace{5pt}}ccc} ',
  '\\toprule', 
  '& \\multicolumn{2}{c}{Experiment 3} \\\\ \\midrule',
  out1[12],
  '\\midrule',
  out1[16:18],
  out1[20], # No Cover mean
  out1[22:23], # Obs, R^2
  '\\midrule',
  '& \\multicolumn{2}{c}{Experiment 4} \\\\ \\midrule',
  out2[12],
  '\\midrule',
  out2[16:18],
  out2[20], # No Cover mean
  out2[22:23], # Obs, R^2
  '\\midrule',
  out3[12],
  '\\midrule',
  out3[16:18],
  out3[20], # No Cover mean
  out3[22:23], # Obs, R^2
  '\\midrule',
  out3[21], # Controls
  out3[24:length(out3)]
)
write_lines(out, str_interp('output/tables/deport-all.tex'))
file.remove('output/tables/deport-sender.tex')



## Figure 3 ##
dodge=0.13
donate = create_summary('believe_donated')
plot = ggplot(donate[[1]], aes(x = expgroup, y =mean, shape=condition)) +
  geom_point(position = position_dodge2(width=0.5), size=3) +
  geom_linerange(aes(ymin = mean-1.96*se, ymax=mean+1.96*se), position = position_dodge2(width=0.5), alpha=0.3, size=0.8) +
  theme_bw() +
  ylab('Fraction believing partner donated') +
  ylim(0, 0.5) +
  labs(shape='Condition') +
  theme(legend.position = 'bottom',
        axis.title.x = element_blank(),
        axis.text.x = element_text(size=11)) +
  ggsignif::geom_signif(
    y_position = c(0.45, 0.45, 0.45), xmin = c(1-dodge, 2-dodge, 3-dodge), xmax = c(1+dodge, 2+dodge, 3+dodge),
    annotation = c(paste0('p=',donate[[2]]), paste0('p=',donate[[3]]), paste0('p=',donate[[4]])), tip_length = 0.02, vjust=-0.25,
  ) 

ggsave('output/figures/pooled-believe-donate.png', width=7, height=3.5, plot=plot)



deny = create_summary('deny')
plot = ggplot(deny[[1]], aes(x = expgroup, y =mean, shape=condition)) +
  geom_point(position = position_dodge2(width=0.5), size=3) +
  geom_linerange(aes(ymin = mean-1.96*se, ymax=mean+1.96*se), position = position_dodge2(width=0.5), alpha=0.3, size=0.8) +
  theme_bw() +
  ylab('Fraction denying partner bonus') +
  ylim(0, 1) +
  labs(shape='Condition') +
  theme(legend.position = 'bottom',
        axis.title.x = element_blank(),
        axis.text.x = element_text(size=11)) +
  ggsignif::geom_signif(
    y_position = c(0.9, 0.9, 0.9), xmin = c(1-dodge, 2-dodge, 3-dodge), xmax = c(1+dodge, 2+dodge, 3+dodge),
    annotation = c(paste0('p=',deny[[2]]), paste0('p=',deny[[3]]), paste0('p=',deny[[4]])), tip_length = 0.04, vjust=-0.25,
  ) 

ggsave('output/figures/pooled-deny.png', width=7, height=3.5, plot=plot)



